import startColMapperTools from "../startColMapperTools";

const sqlFieldColMapperConfig = {
  "input": ["varchar", "char", "nvarchar", "tinytext"],
  "number": ["float", "tinyint", "int", "smallint", "defaultint", "integer", "bigint", "double", "decimal"],
  "datetime": ["year", "date", "time", "timestamp", "datetime"]
}

function getSqlFieldColMapper() {
  let keys = Object.keys(sqlFieldColMapperConfig);
  let length = keys.length;
  let mapper = {}
  for (let i = 0; i < length; i++) {
    let key = keys[i]
    if (!sqlFieldColMapperConfig[key] || sqlFieldColMapperConfig[key].length < 1) {
      continue
    }
    let sqlTypes = sqlFieldColMapperConfig[key];
    let sqlTypesLength = sqlTypes.length;
    for (let j = 0; j < sqlTypesLength; j++) {
      let item = sqlTypesLength[key]
      mapper[item] = key;
    }
  }
  return mapper;
}

function sqlFileToCol(fieldConfig, sqlFieldColMapper) {
  if (!fieldConfig) {
    return null;
  }
  let col = {};
  col.prop = fieldConfig.prop
  col.label = fieldConfig.label && fieldConfig.prop.length > 0 ? fieldConfig.label : fieldConfig.prop
  if (!fieldConfig.type) {
    col.type = "input"
    return col
  }
  if (!sqlFieldColMapper) {
    return col
  }
}

function sqlFieldsToFormConfig(fields, sqlMapper, sqlFieldColMapper = null) {
  if (sqlMapper === null || sqlMapper === undefined) {
    throw new SyntaxError("sqlMapper Cannot be null or undefined")
  }
  if (sqlFieldColMapper === null || sqlFieldColMapper === undefined) {
    sqlFieldColMapper = getSqlFieldColMapper();
  }
  let column = []
  for (let i = 0; i < fields.length; i++) {
    let col = sqlFileToCol(fields[i], sqlFieldColMapper)
    if (!col) {
      continue
    }
    col = startColMapperTools.createCol(col, sqlMapper)
    col.span = 24
    column.push(col)
  }
  return {

    column: column,
  }
}

const ImportDBTableTools = {
  sqlFieldsToFormConfig,
}
export default ImportDBTableTools
